package com.ylz.sjzx.sio.core.rule;


import com.ylz.sjzx.sio.common.core.exception.BusinessException;
import com.ylz.sjzx.sio.core.group.manager.GroupRpc;
import com.ylz.sjzx.sio.core.group.model.CmdMessage;
import com.ylz.sjzx.sio.core.group.model.GroupRegister;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 获取对应的可用的机器集群
 *
 * @author wiqi
 * @version 1.0
 * @date 2020/12/2
 */
public interface ILoadBalancer {


    /**
     * 再平衡
     *
     * @param result
     * @return
     */
    List<GroupRegister> balance(List<GroupRegister> result);

    /**
     * 获取可用的机器群
     *
     * @return
     */
    default List<GroupRegister> getReachableServers(CmdMessage cmdMessage) {
        List<GroupRegister> result = new ArrayList<>(GroupRpc.serviceAddr.values());

        //发送到什么组
        if (StringUtils.isEmpty(cmdMessage.getToGroupName())) {
            result = result.stream().filter(groupRegister -> groupRegister.getGruopRole().equals(cmdMessage.getToGroupRole())).collect(Collectors.toList());

        }
        //发送到什么角色
        if (StringUtils.isEmpty(cmdMessage.getToGroupRole())) {
            result = result.stream().filter(groupRegister -> groupRegister.getGruopRole().equals(cmdMessage.getToGroupRole())).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(result)) {

            throw new BusinessException("没有可用的服务实例{}");
        }
        //获取对应所有实例再平衡
        return balance(result);
    }
}
